var lat=61.68
var lon=26.37
var zoom=7;
var second=1000;
var users = null;
var map;
var kml = null;
var first_center = 0;
var follow_device = null;
var open_popups = new Array();

function isIE() {
	return /msie/i.test(navigator.userAgent) && !/opera/i.test(navigator.userAgent);
}

function init(requrl) {
	/*  Create map-object */
	map = new OpenLayers.Map ("map", {
			controls:[
				new OpenLayers.Control.Navigation(),
				new OpenLayers.Control.PanZoomBar(),
				new OpenLayers.Control.LayerSwitcher(),
				new OpenLayers.Control.KeyboardDefaults()],
			maxExtent: new OpenLayers.Bounds(-20037508.34,-20037508.34,20037508.34,20037508.34),
			maxResolution: 156543.0399,
			numZoomLevels: 19,
			units: 'm',
			projection: new OpenLayers.Projection("EPSG:900913"),
			displayProjection: new OpenLayers.Projection("EPSG:4326")
		} );


	/* Specify layers for map and KML layer for users*/
	layerMapnik = new OpenLayers.Layer.OSM.Mapnik("Mapnik");
	layerOsmarender = new OpenLayers.Layer.OSM.Osmarender("Osmarender");
	layerCycleMap = new OpenLayers.Layer.OSM.CycleMap("CycleMap");

	users = new OpenLayers.Layer.Vector("Users", {
		projection: map.displayProjection,
		eventListeners: { 'loadend': userLoadFinished },
		strategies: [new OpenLayers.Strategy.Fixed()],
		protocol: new OpenLayers.Protocol.HTTP({
			url: "xml.php"+"?"+Math.random(),
			format: new OpenLayers.Format.KML({
				extractStyles: true,
				extractAttributes: true
			})
		})
	});

	/* OpenLayers examples */
        select = new OpenLayers.Control.SelectFeature(users);
        users.events.on({
            "featureselected": onFeatureSelect,
            "featureunselected": onFeatureUnselect
        });

        map.addControl(select);
        select.activate();
	/* /end of OpenLayers examples */


	map.addLayers([layerMapnik, layerOsmarender, layerCycleMap, users]);

	if( ! map.getCenter() ){
		var lonLat = new OpenLayers.LonLat(lon, lat).transform(new OpenLayers.Projection("EPSG:4326"), map.getProjectionObject());
		map.setCenter (lonLat, zoom);
	}

	if (requrl != null) {
		loadKML(requrl)
		// autoUpdateTrack();
	}
	autoUpdate();
}

function dumpProps(obj, parent) {
   // Go through all the properties of the passed-in object
   for (var i in obj) {
      // if a parent (2nd parameter) was passed in, then use that to
      // build the message. Message includes i (the object's property name)
      // then the object's property value on a new line
      if (parent) { var msg = parent + "." + i + "\n" + obj[i]; } else { var msg = i + "\n" + obj[i]; }
      // Display the message. If the user clicks "OK", then continue. If they
      // click "CANCEL" then quit this level of recursion
      if (!confirm(msg)) { return; }
      // If this property (i) is an object, then recursively process the object
      if (typeof obj[i] == "object") {
         if (parent) { dumpProps(obj[i], parent + "." + i); } else { dumpProps(obj[i], i); }
      }
   }
}

function getPropertyCount(obj) {
  var i, v;
  var count = 0;
  var props = [];
  if (typeof(obj) === 'object') {
    for (i in obj) {
      v = obj[i];
      if (v !== undefined && typeof(v) !== 'function') {
        props[count] = i;
        count++;
      }
    }
  }
  return count;
};


function autoUpdate() {
	users.refresh(true);

	setTimeout("autoUpdate()",10*second);
	setTimeout("usersUpdated()", 3*second);
}

function usersUpdated() {
	a = map.popups.length;
	for (var i=0; i < a; i++) {
 		map.removePopup(map.popups[0]);
	}


	for (var i=0; i < open_popups.length; i++) {
		for (var a=0; a<getPropertyCount(users.features);a++) {
			var username= users.features[a].attributes.name;
			var device_id= users.features[a].attributes.device;
				if (device_id == open_popups[i]) {
			    var feature = users.features[a]
			    var content = feature.attributes.description;
					if (follow_device == device_id) {
						content = content + '<a href="#" onclick="stopfollowdevice(\''+device_id+'\')">Stop following this user</a>';
					} else {
						content = content + '<a href="#" onclick="followdevice(\''+device_id+'\')">Follow this user</a>';
					}
			    popup = new OpenLayers.Popup.FramedCloud(device_id, 
	                             feature.geometry.getBounds().getCenterLonLat(),
	                             new OpenLayers.Size(100,100),
	                             content,
	                             null, true, onPopupClose);
		    map.addPopup(popup);
			}
		}
	}	

	for (var a=0; a<getPropertyCount(users.features);a++) {
		var device_id= users.features[a].attributes.device;
		if (follow_device == device_id) {
			map.setCenter (users.features[a].geometry.getBounds().getCenterLonLat());
		}
	}
}

function autoUpdateTrack() {
	kml.refresh(true);
	setTimeout("autoUpdateTrack()",30*second);
}

function followdevice(device_id) {
	follow_device = device_id;
}

function stopfollowdevice(device_id) {
	follow_device = null;
}
function onPopupClose(evt) {
	if (isIE() == true) {
	  for (var i=0; i < open_popups.length; i++) {
			if (open_popups[i] == evt.srcElement.parentNode.parentNode.id) {
				open_popups.splice(i,1);
			}
	  }
	  for (var i=0; i < map.popups.length; i++) {
	  	if (map.popups[i].id == evt.srcElement.parentNode.parentNode.id) {
	  		map.removePopup(map.popups[i]);
	  	}
	  }
	} else {
	  for (var i=0; i < open_popups.length; i++) {
			if (open_popups[i] == evt.target.parentNode.parentNode.id) {
				open_popups.splice(i,1);
			}
	  }
	  for (var i=0; i < map.popups.length; i++) {
	  	if (map.popups[i].id == evt.target.parentNode.parentNode.id) {
	  		map.removePopup(map.popups[i]);
	  	}
	  }
	}
}


function onFeatureSelect(event) {
    var feature = event.feature;
    var username = feature.attributes.name;
    var device_id = feature.attributes.device;
    var content = feature.attributes.description;
		if (follow_device == device_id) {
			content = content + '<a href="#" onclick="stopfollowdevice(\''+device_id+'\')">Stop following this user</a>';
		} else {
			content = content + '<a href="#" onclick="followdevice(\''+device_id+'\')">Follow this user</a>';
		}
    popup = new OpenLayers.Popup.FramedCloud(feature.attributes.device, 
                             feature.geometry.getBounds().getCenterLonLat(),
                             new OpenLayers.Size(100,100),
                             content,
                             null, true, onPopupClose);
    feature.popup = popup;
    open_popups.push(feature.attributes.device);
    map.addPopup(popup);
}

function onFeatureUnselect(event) {
}

function loadKML(requrl, name) {
	if ( kml != null ) {
		map.removeLayer(kml);
	}
	var url = "";
	if (requrl != null) {
		url = requrl;
	} else {
		url = prompt("Give url for KML file","http://whiz.iki.fi/kml/2009-05-27_234644.kml");
	}
	if (name == null) {
		name = "KML: "+url;
	}
	//alert(name);
	kml = new OpenLayers.Layer.Vector(name, {
		projection: map.displayProjection,
		strategies: [new OpenLayers.Strategy.Fixed()],
		eventListeners: { 'loadend': kmlLoadFinished },
		protocol: new OpenLayers.Protocol.HTTP({
			url: encodeURI(url)+"?"+Math.random(),
			format: new OpenLayers.Format.KML({
				extractStyles: true,
				extractAttributes: true
			})
		})
	});
                
	map.addLayer(kml);
	// setTimeout("autoUpdateTrack()",30*second);
	map.raiseLayer(kml, -1);
}


function kmlLoadFinished () {
	map.zoomToExtent(kml.getDataExtent());
}


// unnecessary, need to merge with previous function if possible
function userLoadFinished () {
	if ( first_center == 0 ) {
		map.zoomToExtent(users.getDataExtent());
		first_center = 1;
	}
}


function login() {
	var username = $("#username").val();
	var password = $("#password").val();
	$.post("index.php?page=login", { 	username: username, 
				password: password }, function(data) {
					$("#status p").html(data);
				});
	return false;
}

function viewtrack(site_url, device_id, first_id, last_id, track_id, username) {
	var url = site_url+"/track.php?track_id="+track_id+"&device_id="+device_id+"&first_id="+first_id+"&last_id="+last_id;
	name = "Track "+track_id+", user: "+username;
	loadKML(url, name);

	tb_remove();
	return false;

}

function trackinfo(track_id) {
	
}

